Call by Value and Call by Reference in C++

Posted on December 14, 2023 by Vishesh Namdev
Python C C++ Java
C++ Programming

Function arguments can be passed to functions using either "call by value" or "call by reference." These terms refer to how the values of the arguments are passed to the function

Functions can be categorized into two main types based on parameters, functions with parameters and functions without parameters.

Call by Value

In call by value, the actual values of the arguments are passed to the function. The function works with a copy of the values, and any changes made to the parameters inside the function do not affect the original values outside the function. Simple data types like int, float, char, etc., are typically passed by value.

// Include necessary header
#include <iostream>

// Function to square a number
void square(int x) {
    x = x * x;
    std::cout << "Inside function: " << x << "\n";
}

// Main function
int main() {
    int num = 5;
    square(num);
    std::cout << "Outside function: " << num << "\n";
    return 0;
}

Output

Inside function: 25
Outside function: 5

In this example, the value of num remains unchanged outside the function despite being squared inside the function.

Call by Reference

In call by reference, the memory address (reference) of the actual arguments is passed to the function. The function can directly access and modify the values at the memory locations of the parameters, leading to changes reflected outside the function. Reference parameters are indicated using the & symbol in the function declaration

// Include necessary header
#include <iostream>

// Function to square a number by reference
void squareByReference(int &x) {
    x = x * x;
    std::cout << "Inside function: " << x << "\n";
}

// Main function
int main() {
    int num = 5;
    squareByReference(num);
    std::cout << "Outside function: " << num << "\n";
    return 0;
}

Output

Inside function: 25
Outside function: 25

In this example, the value of num is changed outside the function because the function works directly with the reference to the variable.